package com.jvyou.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author 橘柚
 * @version 1.0-SNAPSHOT
 * @Date 2024/7/17 19:12
 * @Description
 */
public class BatchInsert {

    public static void insert1() throws SQLException {
        long start = System.currentTimeMillis();
        String url = "jdbc:mysql://localhost:3306/jvyou-mybatis";
        String username = "root";
        String password = "123456";
        Connection conn = DriverManager.getConnection(url, username, password);
        PreparedStatement ps = conn.prepareStatement("insert into user(name, age, email) values(?, ?, ?)");
        // 循环插入 1 万条数据
        for (int i = 0; i < 10000; i++) {
            ps.setString(1, "jvyou" + i);
            ps.setInt(2, 18 + i);
            ps.setString(3, "jvyou" + i + "@gmail.com");
            ps.executeUpdate();
        }
        ps.close();
        conn.close();
        System.out.println("耗时：" + (System.currentTimeMillis() - start));
    }

    public static void insert2() throws SQLException {
        long start = System.currentTimeMillis();
        String url = "jdbc:mysql://localhost:3306/jvyou-mybatis?rewriteBatchedStatements=true";
        String username = "root";
        String password = "123456";
        Connection conn = DriverManager.getConnection(url, username, password);
        PreparedStatement ps = conn.prepareStatement("insert into user(name, age, email) values(?, ?, ?)");
        // 循环插入 1 万条数据
        for (int i = 0; i < 10000; i++) {
            ps.setString(1, "jvyou" + i);
            ps.setInt(2, 18 + i);
            ps.setString(3, "jvyou" + i + "@gmail.com");
            // 添加到批处理
            ps.addBatch();
        }
        ps.executeBatch();
        ps.close();
        conn.close();
        System.out.println("耗时：" + (System.currentTimeMillis() - start));
    }

    public static void main(String[] args) throws SQLException {
        insert2();
    }
}
